package com.tj.jinzao.fragment;

import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.tj.jinzao.R;
import com.tj.jinzao.adapter.ZXSAdapter;
import com.tj.jinzao.api.ApiRetrofit;
import com.tj.jinzao.api.ApiService;
import com.tj.jinzao.api.SubscriberCallBack;
import com.tj.jinzao.base.BaseDataListFragment;
import com.tj.jinzao.callback.ITalkFriendView;
import com.tj.jinzao.manager.UserManager;
import com.tj.jinzao.model.FriendBean;
import com.tj.jinzao.model.ResultResponse;
import com.tj.jinzao.model.User;
import com.tj.jinzao.presenter.ZXSPresenter;
import com.tj.jinzao.utils.ToastUtils;
import com.tj.jinzao.widgets.EmptyView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * 搜索咨询师
 * Created by wjy on 2019/1/1.
 */
public class ZXSFragment extends BaseDataListFragment<List<FriendBean>, ZXSPresenter, FriendBean> implements ITalkFriendView<List<FriendBean>> {

    @BindView(R.id.fl_list_layout)
    View mListLayout;

    private User user;

    public static ZXSFragment newInstance() {
        ZXSFragment fragment = new ZXSFragment();
        if (fragment != null) {
            Bundle args = new Bundle(3);
            args.putString(ARG_TAG_ID, "1");
            args.putInt(ARG_LOAD_ID, 1);
            args.putInt(ARG_LAYOUT_RES_ID, R.layout.friend_fragment);
            fragment.setArguments(args);
        }

        return fragment;
    }

    @Override
    public void onRequestNoData(String message) {
        setEmptyDataView();
    }

    @Override
    protected ZXSPresenter createPresenter() {
        user= UserManager.getInstance().getUser();
        return new ZXSPresenter(this);
    }

    @Override
    protected void createView(LayoutInflater inflater, View view) {

    }

    @Override
    protected RecyclerView.Adapter createAdapter() {
        return new ZXSAdapter(mContext, mData,2);
    }

    @Override
    protected void requestData() {
         HashMap<String,Object> map=new HashMap<>();
         map.put("keyword","");
         mPresenter.getTalk(map);
    }


    @Override
    protected void setEmptyDataView() {
        mEmptyView.setVisibility(View.VISIBLE);
        mEmptyView.setState(EmptyView.State.NO_DATA, "");
    }

    @Override
    public void onRequestSuccess(List<FriendBean> friendBeans) {
        super.onRequestSuccess(friendBeans);
        if (mPageNo <= 1) {
            mData.clear();
        }
        mData.addAll(friendBeans);
        for (int i=0;i<mData.size();i++){
            if(mData.get(i).getId().equals(String.valueOf(user.getId()))){
                mData.remove(i);
            }
        }
        showListView();
    }
    protected ApiService mApiService = ApiRetrofit.getInstance().getApiService();

    private CompositeSubscription mCompositeSubscription;


    public void detachView() {
        onUnsubscribe();
    }
    public void addSubscription(Observable observable, Subscriber subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

    //RXjava取消注册，以避免内存泄露
    public void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        detachView();
    }

    @Override
    protected boolean resolveData(List<FriendBean> friendBeans) {
        return false;
    }

    @Override
    protected void initData() {
    }
    private FriendBean datas;

    @Override
    protected void itemClicked(int position, FriendBean data) {
        for (int i=0;i<mData.size();i++){
            mData.get(i).setSelect(false);
        }
        mData.get(position).setSelect(true);
        mListView.getAdapter().notifyDataSetChanged();
        this.datas=data;
//        startActivity(new Intent(mContext, ArticleDetailActivity.class).putExtra("article", data));
    }
    private String nickName,userId;
    public void configChat(String nickName,String userId){
        this.nickName=nickName;
        this.userId=userId;
        addSubscription(mApiService.getYunXinById(userId), new SubscriberCallBack<User>(getActivity()) {
            @Override
            protected void onSuccess(User user) {
                HashMap<String,Object> map=new HashMap<>();
                map.put("uid",user.getId());
                map.put("counselor",datas.getId());
                Log.w("用户分配数据",""+map.toString());
                mPresenter.getTalkFriend(map);

            }

            @Override
            protected void onFailure(ResultResponse response) {
            }

            @Override
            protected boolean isShowProgress() {
                return false;
            }

            @Override
            protected void onPageSuccess(int currentPage, int allPage, int allSize) {
            }
        });


    }



    @Override
    public void onRequestSuccessPage(int currentPage, int allPage, int allSize) {

    }

    @Override
    public void onReload(Object tag) {

    }

    @Override
    public void onTalkSuccess(String friendBean) {
        if(userId==null||userId.equals("")){
            ToastUtils.showToast(getActivity(),"分配失败");
            return;
        }
        ToastUtils.showToast(getActivity(),"分配成功");
        SessionTypeEnum sessionType = SessionTypeEnum.P2P;
        IMMessage textMessage = MessageBuilder.createTextMessage(datas.getId(), sessionType, "已将"+nickName+"分配到您的名下");
        Map<String, Object> data = new HashMap<>();
        data.put("messageType", "3");
        data.put("messagePosition", "0");
        data.put("userNickName", nickName);
        data.put("userId", userId);
        data.put("fromUserId", datas.getId());
        textMessage.setRemoteExtension(data);
        NIMClient.getService(MsgService.class).sendMessage(textMessage, false);
        getActivity().finish();
    }


    @Override
    public void onFailed(ResultResponse response) {
        if(response.getCode().equals("00")){
            SessionTypeEnum sessionType = SessionTypeEnum.P2P;
            IMMessage textMessage = MessageBuilder.createTextMessage(datas.getId(), sessionType, "已将"+nickName+"分配到您的名下");
            Map<String, Object> data = new HashMap<>();
            data.put("messageType", "3");
            data.put("messagePosition", "0");
            data.put("userNickName", nickName);
            data.put("userId", userId);
            data.put("fromUserId", datas.getId());
            textMessage.setRemoteExtension(data);
            NIMClient.getService(MsgService.class).sendMessage(textMessage, false);
            getActivity().finish();
        }else {
            ToastUtils.showToast(getActivity(),response.getMessage());
        }
    }

    @Override
    public void onUserInfoSuccess(User user) {

    }

    @Override
    public void onUserInfoFailed(ResultResponse response) {

    }
}
